//
//  GLViewController.mm
//  Blend
//
//  Created by wq on 11-8-24.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GLViewController.h"
#import "GLView.h"
#import "glues.h"

@interface GLViewController ()

@property(nonatomic, retain) EAGLContext *context;
@property(nonatomic, assign) CADisplayLink *dispLink;

-(void)drawFrame;

@end


@implementation GLViewController

@synthesize animating;
@dynamic frameInterval;

@synthesize context;
@synthesize dispLink;

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	[super viewDidUnload];
}

- (void)dealloc {
	[context release];
	[super dealloc];
}

-(id)init {
	self = [super init];
	if (self) {
		EAGLContext *ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
		self.context = ctx;
		[ctx release];
		
		GLView *v = [[GLView alloc] initWithFrame:[UIScreen mainScreen].bounds];
		self.view = v;
		[v release];
		
		v.context = context;
		[v initViewport];
		
		animating = NO;
		frameInterval = 2;
	}
	return self;
}

-(void)startAnimation {
	if (!animating) {
		CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawFrame)];
		self.dispLink = displayLink;
		[displayLink setFrameInterval:frameInterval];
		[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
		animating = YES;
	}
}

-(void)stopAnimation {
	if (animating) {
		[dispLink invalidate];
		self.dispLink = nil;
		animating = NO;
	}
}

-(void)drawFrame {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	
	gluLookAtf(0.0f, 0.0f, 415.6921938165306f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	
	// 1. 无混色
	glDisable(GL_BLEND);
	
	glPushMatrix();
	glTranslatef(-80.f, 120.f, 0.f);
	glScalef(0.5f, 0.5f, 1.f);
	static const GLfloat points[] = {
		-100.f, -100.f, 0.f,
		100.f, -100.f, 0.f,
		-100.f, 100.f, 0.f,
		100.f, 100.f, 0.f,
	};
	
	glColor4f(1.f, 0.f, 0.f, 1.f);
	
	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(3, GL_FLOAT, 0, points);
	
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
	static GLfloat transX = 0.f;
	
	static GLfloat stepX = 10.f;
	
	transX += stepX;
	
	if (transX > 200.f) {
		stepX = -10.f;
	} else if (transX < -200.f) {
		stepX = 10.f;
	}
	
	glColor4f(0.f, 1.f, 0.f, 1.f);
	glScalef(0.5f, 0.5f, 1.f);
	glTranslatef(transX, 0.f, 0.f);
	
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glPopMatrix();
	
	// 2. 开启混色
	glEnable(GL_BLEND);
	// 默认值
	glBlendFunc(GL_ONE, GL_ZERO);
	
	glPushMatrix();
	glTranslatef(80.f, 120.f, 0.f);
	glScalef(0.5f, 0.5f, 1.f);
	
	glColor4f(1.f, 0.f, 0.f, 1.0f);
	
	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(3, GL_FLOAT, 0, points);
	
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
	// 基于源像素alpha通道值
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	
	glColor4f(0.f, 1.0f, 0.f, 1.f);
	glScalef(0.5f, 0.5f, 1.f);
	glTranslatef(transX, 0.f, 0.f);
	
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glPopMatrix();
	
	[(GLView *)self.view presentRenderbuffer];
}

@end
